import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 张杰
 * Date: 2022-03-30
 * Time: 16:11
 */
public class TestJDBCUpdate {
    public static void main(String[] args) throws SQLException {
        //根据学生id来修改学生姓名,需要输入的是要修改的id和修改之后的名字
        //1.创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java102?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");

        //2.和数据库建立连接
        Connection connection = dataSource.getConnection();

        //3.输入数据
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要修改的学生id: ");
        int id = scanner.nextInt();
        System.out.println("请输入要修改的学生姓名: ");
        String name = scanner.next();

        //4.拼装 sql
        String sql = "update student set name = ? where id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,name);//1,2和问号的位置相对应
        statement.setInt(2,id);
        System.out.println("statment: "+statement);

        //5.执行sql
        int ret = statement.executeUpdate();
        System.out.println("ret = "+ ret);

        //6.回收释放资源
        statement.close();
        connection.close();
    }
}
